package com.hnust.controller;


import com.hnust.domain.record.GeneratePapaerInfoRecord;
import com.hnust.service.PaperService;
import com.hnust.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.rmi.server.ExportException;

@CrossOrigin("*")
@RestController
@RequestMapping("/download")
public class DownloadController {

	@Autowired
	PaperService paperService;

	/*
	 * @Author Tonited
	 * @Description //TODO 获取导入题目的模板
	 * @Date 19:29 2020/10/30
	 * @Param [request, response]
	 * @return void
	 **/
	@GetMapping("question")
	public Result<Object> getQuestionTemple(HttpServletRequest request , HttpServletResponse response) throws IOException {
		String msg = "获取成功";
		int code = 1;
		try {
			getFile(request,response,"批量导入题目模板","example");
		}catch (Exception e){
			code = 0;
			msg = e.getMessage();
		}
		return new Result<>(code,msg,null);

	}


	/*
	 * @Author Tonited
	 * @Description //TODO 生成是试卷、试卷预览和出题计划表，返回试卷的ID，并将试卷记录存入数据库
	 * @Date 16:53 2020/10/31
	 * @Param [request, response, info]
	 * @return com.hnust.util.Result<java.lang.String>
	 **/
	/*测试数据
		{
    "teacherId": "as8x145fdb",
    "collegeId": "1",
    "courseNumber": "a10",
    "examTime": "100分",
    "grade": "2018",
    "type": "A",
    "questions": [
        {
            "questionID":"123",
            "score":5
        },{
            "questionID":"2",
            "score":12
        },{
            "questionID":"5",
            "score":7
        },{
            "questionID":"123",
            "score":5
        },{
            "questionID":"2",
            "score":12
        },{
            "questionID":"5",
            "score":7
        }
    ]
}
	 */
	@PostMapping("create")
	public Result<String> createPaper(HttpServletRequest request , HttpServletResponse response, @RequestBody GeneratePapaerInfoRecord info) throws IOException {
		String id = null;
		String msg = "获取成功";
		int code = 1;
		try {
			id = paperService.getPaperPreview(info);

		}catch (Exception e){
			code = 0;
			msg = e.getMessage();
		}
		return new Result<>(code,msg,id);
	}

	/*
	 * @Author Tonited
	 * @Description //TODO 根据试卷ID下载试卷的预览图片
	 * @Date 16:53 2020/10/31
	 * @Param [request, response, paperId]
	 * @return void
	 **/
	@GetMapping("paperpdf")
	public Result<Object> getPaperPreview(HttpServletRequest request , HttpServletResponse response, @RequestParam("paperId") String paperId ){
		String msg = "获取成功";
		int code = 1;
		try {
			getFile(request,response,paperId,"pdf");
		}catch (Exception e){
			code = 0;
			msg = e.getMessage();
		}
		return new Result<>(code,msg,null);
	}

	/*
	 * @Author Tonited
	 * @Description //TODO 根据试卷ID下载试卷文档
	 * @Date 16:53 2020/10/31
	 * @Param [request, response, paperId]
	 * @return void
	 **/
	@GetMapping("paperdocx")
	public void getPaperDocx(HttpServletRequest request , HttpServletResponse response, @RequestParam("paperId") String paperId ) throws IOException {
		getFile(request,response,paperId,"paper");
	}

	/*
	 * @Author Tonited
	 * @Description //TODO 根据试卷ID下载出题计划表
	 * @Date 20:16 2020/11/1
	 * @Param [request, response, paperId]
	 * @return void
	 **/
	@GetMapping("paperplan")
	public void getPaperPlan(HttpServletRequest request , HttpServletResponse response, @RequestParam("paperId") String paperId ) throws IOException {
		getFile(request,response,paperId,"plan");
	}

	@GetMapping("paperanswer")
	public void getPaperAnswer(HttpServletRequest request , HttpServletResponse response, @RequestParam("paperId") String paperId ) throws IOException {
		getFile(request,response,paperId,"answer");
	}

	/*
	 * @Author Tonited
	 * @Description //TODO 获取文件的工具方法
	 * @Date 9:47 2020/10/31
	 * @Param type{"example","paper","pdf","plan","answer"}
	 * @return
	 **/
	private void getFile(HttpServletRequest request , HttpServletResponse response, String fileName, String type) throws IOException {
		String typeTile = null;
		if("pdf".equals(type)){
			typeTile = "pdf";
		}else{
			typeTile="docx";
		}
		File file = new File(System.getProperty("user.dir") + "/assets/"+type);
		if(!file.exists()) {

			file.mkdir();
		}
		String filePath = System.getProperty("user.dir") + "/assets/"+type+"/"+fileName+"."+typeTile;
		response.setCharacterEncoding("UTF-8");
		fileName = URLEncoder.encode(fileName,"UTF-8");
		response.setHeader("Content-disposition", "attachment; filename="+fileName+"."+typeTile);
		//根据路径获取文件
		File docFile = new File(filePath);
		//获取文件后缀名格式
		String ext = docFile.getName().substring(docFile.getName().indexOf("."));
		//判断图片格式,设置相应的输出文件格式
		if(ext.equals("jpg")){
			response.setContentType("image/jpeg");
		}else if(ext.equals("JPG")){
			response.setContentType("image/jpeg");
		}else if(ext.equals("png")){
			response.setContentType("image/png");
		}else if(ext.equals("PNG")){
			response.setContentType("image/png");
		}else if(ext.toLowerCase().equals("doc")){
			response.setContentType("application/msword");
		}else if(ext.toLowerCase().equals("docx")){
			response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
		}
		//读取指定路径下面的文件
		InputStream in = new FileInputStream(docFile);
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		//创建存放文件内容的数组
		byte[] buff =new byte[1024];
		//所读取的内容使用n来接收
		int n;
		//当没有读取完时,继续读取,循环
		while((n=in.read(buff))!=-1){
			//将字节数组的数据全部写入到输出流中
			outputStream.write(buff,0,n);
		}
		//强制将缓存区的数据进行输出
		outputStream.flush();
		//关流
		outputStream.close();
		in.close();
	}
}
